package main

import (
	"errors"
	"fmt"
	"gitee.com/showurl/push-rtmp/config"
	"gitee.com/showurl/push-rtmp/db"
	"gitee.com/showurl/push-rtmp/models"
	"gitee.com/showurl/push-rtmp/utils"
	"gorm.io/gorm"
	"log"
	"os/exec"
	"strings"
	"time"
)

func getNowMp4() (*models.ModelCurrentInfo, error) {
	find := &models.ModelCurrentInfo{}
	err := db.DB.Model(find).Order("id desc").First(find).Error
	return find, err
}

func pushCmd(
	seconds int, mp4Path string, text string, rtmpAddress string,
) string {
	switch config.Config.PushCmdSetting {
	case "show-text":
		return fmt.Sprintf(
			`ffmpeg -re -ss %d -i "%s" -vf "drawtext=fontfile='/usr/share/fonts/chinese/Arial Unicode.ttf': text='%s':x=17:y=542:fontsize=17:fontcolor=white:shadowy=2" -vcodec libx264 -acodec copy -f flv "%s"`,
			seconds, mp4Path, text, rtmpAddress,
		)
	default:
		return fmt.Sprintf(
			`ffmpeg -re -ss %d -i "%s" -vcodec copy -acodec copy -f flv "%s"`,
			seconds, mp4Path, rtmpAddress,
		)
	}

}

func play(mp4Path string, rtmpAddress string) (*time.Ticker, error) {
	find, err := getNowMp4()
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			err = nil
		} else {
			return nil, err
		}
	}
	var seconds = 0
	if find.ID == 0 {
		// 没找到
	} else {
		// 找到了
		// 看看是不是当前视频
		if find.Mp4Path == mp4Path {
			if find.HealthSeconds >= find.Seconds-config.Config.HealthInterval*2 {
				// 我就算他播完了 重新播
			} else {
				// 没播完 需要接着播放
				seconds = find.HealthSeconds
			}
		}
	}
	if seconds == 0 {
		duration, err := utils.GetMP4Duration(mp4Path)
		if err != nil {
			return nil, err
		}
		// 添加一条记录
		find = &models.ModelCurrentInfo{
			Mp4Path:       mp4Path,
			Seconds:       int(duration),
			StartPlayTime: time.Now(),
			HealthSeconds: 0,
		}
		err = db.DB.Model(find).Create(find).Error
		if err != nil {
			return nil, err
		}
	}
	// 更新find
	ticker := time.NewTicker(time.Duration(config.Config.HealthInterval) * time.Second)
	go func() {
		for {
			t := <-ticker.C
			runSeconds := t.Sub(find.StartPlayTime).Seconds()
			var healthSeconds = int(runSeconds)
			if runSeconds >= float64(find.Seconds) {
				// 停止
				ticker.Stop()
				healthSeconds = find.Seconds
				err = db.DB.Model(find).Where("id = ?", find.ID).Updates(map[string]interface{}{
					"health_seconds": healthSeconds,
				}).Error
				if err != nil {
					log.Println(err.Error())
				}
				break
			}
			err = db.DB.Model(find).Where("id = ?", find.ID).Updates(map[string]interface{}{
				"health_seconds": healthSeconds,
			}).Error
			if err != nil {
				log.Println(err.Error())
			}
		}
	}()
	cmd := exec.Command("sh", "-c",
		pushCmd(seconds, mp4Path, fmt.Sprintf("%s %d秒", strings.TrimSuffix(strings.Split(mp4Path, "/")[len(strings.Split(mp4Path, "/"))-1], ".mp4"), seconds), rtmpAddress),
	)
	err = utils.Command(cmd)
	if err != nil {
		return ticker, err
	}
	return ticker, nil
}
